
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { BaseService } from '@/common/base/service';

import { RoleEntity } from './entities/role.entity';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { QueryRoleDto } from './dto/query-role.dto';

@Injectable()
export class RoleService extends BaseService<RoleEntity> {
  constructor(
    @InjectRepository(RoleEntity)
    private repo: Repository<RoleEntity>,
  ) {
    super(repo);
  }

  async create(createDto: CreateRoleDto): Promise<RoleEntity> {
    const exist = await this.repo.findOne({ where: { name: createDto.name } });
    if (exist) {
      throw new Error(`role已存在`);
    }
    return this.repo.save(createDto);
  }

  async findAll(query: QueryRoleDto) {
    return this.paginate(query, ['name'], [], { id: 'DESC' });
  }

  async findOne(id: number): Promise<RoleEntity> {
    const item = await this.repo.findOne({ where: { id } });
    if (!item) {
      throw new Error(`未找到id为${id}的role`);
    }
    return item;
  }

  async update(id: number, updateDto: UpdateRoleDto): Promise<RoleEntity> {
    const item = await this.findOne(id);
    Object.assign(item, updateDto);
    return this.repo.save(item);
  }

  async remove(id: number) {
    const res = await this.repo.delete(id);
    if (res.affected === 0) {
      throw new Error(`未找到id为${id}的role`);
    }
    return { message: 'role已删除' };
  }
}
